import 'package:flutter/material.dart';
import '../model/msg_list.model.dart';
import 'package:ninetyfour/l10n/app_localizations.dart';
import '../../manger/network_utils.dart';
import '../../components/toast_utils.dart';
import 'package:provider/provider.dart';
import '../../services/global_state.dart';
import '../../manger/qysdk_manger.dart';
class MsgListView extends StatefulWidget {
  const MsgListView({super.key});
  @override
  _MsgListViewState createState() => _MsgListViewState();
}

class _MsgListViewState extends State<MsgListView> {
  bool isNeedClear = false;
  List<RecordsModel> msgList = [];
  @override
  void initState() {
    super.initState();
    getMsgInfo();
  }

  Future<void> getMsgInfo() async {
    if (!mounted) return;
    
    isNeedClear = false;
    final response = await NetworkUtils.get(
      RequestCmd.msgOrderList,
      params: {'pageNum': 1,'pageSize': 10,'messageType': 0},
    );
    ToastUtils.dismissLoadingToast();
          
    final model = MsgOrderDataModel.fromJson(response);
    if (model.code == 200) {
      setState(() {
        msgList = model.data.records;
        isNeedClear = msgList.any((record) => record.messageStatus == 1);
      });
    }
  }

  void clearNow(int msgId) async{
    try {
      final response = await NetworkUtils.post(
        RequestCmd.messagesread,
        body: {"type": 2,"idList":[msgId]},
      );
      ToastUtils.dismissLoadingToast();

      if (response['code'] == 200) {
        Provider.of<GlobalState>(context, listen: false).updateMessageDeleteOne;
        getMsgInfo();
      } 
    } catch (e) {
      ToastUtils.dismissLoadingToast();
      print(e);
    }
  }

  void clearAll() async{
    try {
      final response = await NetworkUtils.post(
        RequestCmd.messagesread,
        body: {"type": 0},
      );
      ToastUtils.dismissLoadingToast();

      if (response['code'] == 200) {
        getMsgInfo();
        Provider.of<GlobalState>(context, listen: false).updateMessageCount(0);
        ToastUtils.showCenterToast(context, AppLocalizations.of(context)!.allMessagesIsRead);
      } else {
        ToastUtils.showCenterToast(context, response['msg']);
      }
    } catch (e) {
      ToastUtils.dismissLoadingToast();
      print(e);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          AppLocalizations.of(context)!.orderDynamic,
          style: const TextStyle(fontSize: 17),
        ),
        actions: [
          IconButton(
            icon: Image.asset("assets/images/msgclear.png", width: 20, height: 20),
            onPressed: () {
              if (!isNeedClear) {
                ToastUtils.showCenterToast(context, AppLocalizations.of(context)!.noUnreadMessages);
                return;
              }
              clearAll();
            },
          ),
        ],
      ),
      body: ListView.builder(
        itemCount: msgList.length,
        itemBuilder: (context, index) {
          final record = msgList[index];
          return CustomListItem(
            record: record,
            onTap: () {
              clearNow(record.id);
              showQYSession();
            },
          );
        },
      ),
    );
  }

  void showQYSession() {
    QYSDK.showQYSession();
  }
}

class CustomListItem extends StatelessWidget {
  final RecordsModel record;
  final VoidCallback onTap;

  CustomListItem({required this.record, required this.onTap});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        margin: EdgeInsets.symmetric(vertical: 8, horizontal: 16),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12),
        ),
        padding: EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Text(
                    record.messageTitle,
                    style: TextStyle(fontSize: 16, color: Colors.black),
                  ),
                  if (record.messageStatus != 0)
                    Padding(
                      padding: const EdgeInsets.only(left: 8),
                      child: CircleAvatar(
                        radius: 4,
                        backgroundColor: Colors.red,
                      ),
                    ),
                  Spacer(),
                  Text(
                    record.messageStartTime,
                    style: TextStyle(fontSize: 13, color: Colors.grey),
                  ),
                ],
              ),
              SizedBox(height: 12),
              Container(
                padding: EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: Color(0xFFF8F8F8),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: RichText(
                  text: TextSpan(
                    style: TextStyle(fontSize: 14, color: Colors.black),
                    children: [
                      TextSpan(text: AppLocalizations.of(context)!.orderNumberIs),
                      TextSpan(text: record.messageContent),
                      TextSpan(text: AppLocalizations.of(context)!.orderNumberIs2),
                      WidgetSpan(
                        child: GestureDetector(
                          onTap: onTap,
                          child: Text(
                            AppLocalizations.of(context)!.contact,
                            style: TextStyle(fontSize: 14, color: Colors.blue),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      );  
  }
}
